<template>
    <view class="container">
        <navView navTitle="发票开具" titleColor="#fff" :isBack="true"></navView>
        <view class="containerbox">
            <!-- 合同名称 -->
            <view class="contract-name">
                <text class="title">{{ contractName }}</text>
            </view>
            <view>
                <!-- 数据统计 -->
                <view class="data-statistics">
                    <!-- 标题 -->
                    <view class="title">
                        <view class="tiao"></view>
                        数据统计
                    </view>
                    <!-- 第一组数据 -->
                    <view class="data-row">
                        <view class="data-item">
                            <text class="label">已付金额</text>
                            <text class="value">{{ detail.payment_status.paid_amount }}</text>
                        </view>
                        <view class="data-item">
                            <text class="label">未付金额</text>
                            <text class="value">{{ detail.payment_status.unpaid_amount }}</text>
                        </view>
                        <view class="data-item">
                            <text class="label">待付金额</text>
                            <text class="value">{{ detail.payment_status.pending_payment }}</text>
                        </view>
                    </view>
                    <!-- 第二组数据 -->
                    <view class="data-row">
                        <view class="data-item">
                            <text class="label">已开票金额</text>
                            <text class="value">{{ detail.payment_status.invoiced_amount }}</text>
                        </view>
                        <view class="data-item">
                            <text class="label">未开票金额</text>
                            <text class="value">{{ detail.payment_status.uninvoiced_amount }}</text>
                        </view>
                        <view class="data-item">
                            <text class="label">待开票金额</text>
                            <text class="value">{{ detail.payment_status.pending_invoice }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="containerbox2">
            <view class="contract-details">
                <view class="title">开票信息</view>
                <view class="content">
                    <view class="form-grid">
                        <view class="form-item">
                            <text class="form-label">发票抬头：</text>
                            <text class="form-value">{{ invoice.title || '暂无' }}</text>
                        </view>
                        <view class="form-item">
                            <text class="form-label">发票金额：</text>
                            <text class="form-value money">￥{{ invoice.amount || '0.00' }}</text>
                        </view>
                        <view class="form-item" v-if="this.detail.invoice_type == 0">
                            <text class="form-label">公司名称：</text>
                            <text class="form-value">{{ invoice.company_name || '暂无' }}</text>
                        </view>
                        <view class="form-item" v-if="this.detail.invoice_type == 0">
                            <text class="form-label">单位税号：</text>
                            <text class="form-value">{{ invoice.tax_number || '暂无' }}</text>
                        </view>
                        <view class="form-item" v-if="this.detail.invoice_type == 0">
                            <text class="form-label">注册地址：</text>
                            <text class="form-value">{{ invoice.address || '暂无' }}</text>
                        </view>
                        <view class="form-item" v-if="this.detail.invoice_type == 0">
                            <text class="form-label">开户银行：</text>
                            <text class="form-value">{{ invoice.bank_info || '暂无' }}</text>
                        </view>
                        <view class="form-item" v-if="this.detail.invoice_type == 0">
                            <text class="form-label">银行账号：</text>
                            <text class="form-value">{{ invoice.bank_number || '暂无' }}</text>
                        </view>
                        <view class="form-item full-width">
                            <text class="form-label">发票内容：</text>
                            <text class="form-value">{{ invoice.contant || '暂无' }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 文件上传 -->
            <view class="contract-details upload-section" style="margin-top: 30rpx;">
                <view class="title">文件上传</view>
                <view class="content">
                    <view class="upload-group">
                        <text class="upload-label">开票金额</text>
                        <input class="upload-input" type="number" placeholder="请输入金额" v-model="formData.invoice_money" />
                    </view>

                    <view class="upload-group">
                        <text class="upload-label">附件上传</text>
                        <view class="upload-box">
                            <view class="title">
                                <view class="tiao"></view>
                                附件材料
                            </view>
                            <view class="root">
                                <view class="list-item" v-for="(item, index) in fileList" :key="index">
                                    <image class="file-icon" src="https://hfd.bjlzkj.com/static/list/PDF.png" />
                                    <view class="option">
                                        <view class="file-info">
                                            <view class="file-title">{{ item.name }}</view>
                                            <view class="file-time"></view>
                                        </view>
                                        <view class="action-buttons">
                                            <button class="download-button"
                                                @click="handleDownload(item.url)">下载</button>
                                            <button class="view-button" @click="handleView(item.url)">查看</button>
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <button class="btn upload-btn" @click="uploadFile(true)">上传附件</button>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="footer">
            <button class="submit-btn" @click="submit">完成申请</button>
        </view>
    </view>
</template>

<script>
// 定义全局网络请求
import download from '@/util/filesdownload.js'; //
export default {
    data() {
        return {
            contractName: '此处为合同名称',
            contractCode: 'NO.5689423563548',
            activeState: 1,
            fileList: [
                {
                    name: '',
                    url: '',
                    file_url: '',
                },
            ],
            detail: {},
            invoice: {},
            id: 0,
            contract_id: 0,
            formData: {
                invoice_money: '', // 关联id
                files: "", // 节点id
                id: 0, // 节点id
            },
        };
    },
    onLoad(option) {
        console.log(option, 'option')
        if (option) {
            this.id = option.id
            this.contract_id = option.contract_id
            this.getDetail()
        }
    },
    methods: {
        submit() {
            uni.showModal({
                title: '操作确认',
                content: '确认要开具该发票吗？',
                success: (res) => {
                    if (res.confirm) {                        
                        this.formData.id = this.id
                        // 处理files（添加数组存在性校验）
                        this.formData.files = ""; // 新增重置操作
                        if (this.fileList && this.fileList.length > 0) {
                            this.fileList.forEach(item => {
                                console.log(item)
                                this.formData.files += item.flie_url + ',';
                            });
                            this.formData.files = this.formData.files.replace(/,$/, '');
                        }                        
                        this.$request('/addons/qingdong/invoice/updateInvoiceInfo', 'POST', this.formData).then(res => {
                            if (res.code == 1) {
                                uni.showToast({ title: '开具成功', icon: 'success' });  // 新增失败提示								
                            } else {
                                uni.showToast({ title: res.msg, icon: 'none' });
                            }
                            this.getDetail(); // 重新获取项目进度
                        });
                    } else {
                        uni.showToast({ title: '已取消', icon: 'fail' });
                    }
                }
            });
        },
        getDetail() {
            this.$request('/addons/qingdong/contract/getDetail', 'GET', {
                id: this.contract_id
            }).then(res => {
                console.log(res)
                this.contractName = res.data.name
                this.contractCode = res.data.num
                this.detail = res.data
            })
            this.$request('/addons/qingdong/invoice/getDetail', 'GET', {
                id: this.id
            }).then(res => {
                this.invoice = res.data
                this.formData.invoice_money = res.data.invoice_money
                this.fileList = res.data.files
            })
        },
        handleContractDetails(type) {
            this.activeState = type
        },
        handleDownload(url) {
            download.downloadFun(url);
        },
        handleView(url) {
            // 检查文件是否已下载
            uni.showLoading({ title: '正在打开...' });  // 新增加载提示
            uni.downloadFile({
                url: url,
                success: function (res) {
                    var filePath = res.tempFilePath;
                    uni.openDocument({
                        filePath: encodeURI(filePath),
                        showMenu: true,
                        success: function (res) {
                            uni.hideLoading();  // 隐藏加载提示
                            console.log('打开文档成功', res);
                        },
                        fail: function (err) {
                            uni.hideLoading();  // 隐藏加载提示
                            console.error('打开文档失败', err);
                        }
                    });
                },
                fail: (err) => {
                    uni.hideLoading();  // 隐藏加载提示
                    console.error('下载失败', err);
                    uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
                }
            });
        },
        uploadFile(sw) {
            const token = uni.getStorageSync('user_token');
            uni.chooseImage({
                count: 9,
                type: 'all',
                success: async (res) => {
                    const result = uni.uploadFile({
                        url: 'https://hfd.bjlzkj.com/addons/qingdong/common/upload',
                        filePath: res.tempFilePaths[0],  // 改用tempFilePaths数组中的路径
                        name: 'file',  // 后端接收文件的参数名
                        formData: {
                            category: this.category,  // 添加分类参数
                        },
                        header: {
                            'Content-Type': 'application/json',
                            'token': token // 新增token请求头
                        },
                        success: (uploadFileRes) => {
                            uni.showToast({ title: '上传成功' });
                            try {
                                const resData = JSON.parse(uploadFileRes.data);
                                if (resData && resData.data && resData.data.url) {
                                    console.log(resData.data.flie_url);
                                    this.fileList = [
                                        ...(this.fileList || []),  // 添加空数组保护
                                        {
                                            name: resData.data.url.split('/').pop(),
                                            url: resData.data.url,
                                            flie_url: resData.data.flie_url
                                        }
                                    ];
                                }
                            } catch (e) {
                                console.error('数据解析失败:', e);
                            }
                        },
                        fail: (err) => {
                            console.error('上传失败:', err);
                            uni.showToast({ title: '上传失败', icon: 'none' });
                        },
                    })
                }
            });
        }
    },
};
</script>

<style scoped lang="scss">
.container {
    // 增加垂直排列布局
    display: flex;
    flex-direction: column;
    gap: 30rpx; // 容器间距

    .containerbox2 {
        width: 100%;
        min-height: 30vh; // 改用最小高度
        background: #fff;
        border-radius: 15rpx;
        padding: 30rpx;
        box-sizing: border-box;
        margin-top: 20rpx; // 增加顶部间距
        box-shadow: 0rpx 2rpx 12rpx 2rpx rgba(97, 97, 97, 0.25);
    }

    .contract-details {
        margin: 30rpx 0;
        background: #fff;
        border-radius: 16rpx;
        padding: 30rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

        .title {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            padding-bottom: 20rpx;
            border-bottom: 1rpx solid #eee;
            margin-bottom: 30rpx;
            position: relative;

            &::after {
                content: '';
                position: absolute;
                left: 0;
                bottom: -1rpx;
                width: 80rpx;
                height: 4rpx;
                background: #008EFF;
            }
        }

        .form-grid {
            gap: 30rpx 40rpx;

            .form-item {
                padding: 20rpx 0;
                border-bottom: 1rpx solid #f5f5f5;

                .form-label {
                    color: #666;
                    font-size: 28rpx;
                    margin-bottom: 8rpx;
                }

                .form-value {
                    color: #333;
                    font-size: 30rpx;
                    line-height: 1.4;

                    &.money {
                        color: #FF5722;
                        font-weight: 600;
                    }
                }
            }
        }
    }

    // 文件上传样式优化
    .upload-section {
        .upload-group {
            margin-bottom: 40rpx;

            .upload-label {
                font-size: 30rpx;
                color: #333;
                margin-bottom: 20rpx;
                font-weight: 500;
            }

            .upload-input {
                height: 88rpx;
                background: #f8f8f8;
                border: 1rpx solid #eee;
                border-radius: 12rpx;
                padding: 0 30rpx;
                font-size: 28rpx;
                margin-top: 20rpx;

                &::placeholder {
                    color: #999;
                }
            }

            .upload-box {
                border: 2rpx dashed #e5e5e5;
                border-radius: 16rpx;
                padding: 30rpx;
                margin-top: 20rpx;

                .preview-image {
                    border: 2rpx solid #f0f0f0;
                    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
                }

                .upload-btn {
                    background: #fafafa;
                    border: 2rpx dashed #ddd;

                    &:active {
                        background: #f5f5f5;
                    }
                }
            }
        }
    }

    .containerbox {
        width: 100%;
        height: 30vh;
        background: #fff;
        border-radius: 15rpx;
        padding: 30rpx;
        box-shadow: 0rpx 2rpx 12rpx 2rpx rgba(97, 97, 97, 0.25);
        box-sizing: border-box;

        .contract-name {
            text-align: center;
            margin-bottom: 40rpx;

            .title {
                font-size: 40rpx;
                font-weight: bold;
            }
        }

        .button-group {
            display: flex;
            justify-content: space-around;
            margin-bottom: 40rpx;

            .button {
                color: #666666;
                border: 1rpx solid #B4B4B4;
                border-radius: 10rpx;
                width: 192rpx;
                height: 62rpx;
                line-height: 62rpx;
                background: #FFFFFF;
                border-radius: 6rpx 6rpx 6rpx 6rpx;
                font-size: 28rpx;
                background: #fff;

                &.active {
                    color: #1890ff;
                    border: 1rpx solid #1890ff;
                }
            }
        }

        .data-statistics {
            background-color: #ffffff;
            border-radius: 20rpx;
            margin-bottom: 40rpx;

            .title {
                font-size: 28rpx;
                font-weight: bold;
                margin-bottom: 20rpx;
                display: flex;
                align-items: center;

                .tiao {
                    width: 6rpx;
                    height: 22rpx;
                    background: #1B87E8;
                    border-radius: 8rpx 8rpx 8rpx 8rpx;
                    margin-right: 10rpx;
                }
            }

            .data-row {
                display: flex;
                justify-content: space-around;
                margin-bottom: 20rpx;

                .data-item {
                    display: flex;
                    flex-direction: column;
                    align-items: center;

                    .label {
                        font-size: 28rpx;
                        color: #666666;
                    }

                    .value {
                        font-size: 32rpx;
                        margin-top: 10rpx;
                        font-weight: bold;
                    }
                }
            }
        }

        // 开票信息样式优化
        .contract-details {
            margin: 30rpx 0;
            background: #fff;
            border-radius: 16rpx;
            padding: 30rpx;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

            .title {
                font-size: 32rpx;
                font-weight: 600;
                color: #333;
                padding-bottom: 20rpx;
                border-bottom: 1rpx solid #eee;
                margin-bottom: 30rpx;
                position: relative;

                &::after {
                    content: '';
                    position: absolute;
                    left: 0;
                    bottom: -1rpx;
                    width: 80rpx;
                    height: 4rpx;
                    background: #008EFF;
                }
            }

            .form-grid {
                gap: 30rpx 40rpx;

                .form-item {
                    padding: 20rpx 0;
                    border-bottom: 1rpx solid #f5f5f5;

                    .form-label {
                        color: #666;
                        font-size: 28rpx;
                        margin-bottom: 8rpx;
                    }

                    .form-value {
                        color: #333;
                        font-size: 30rpx;
                        line-height: 1.4;

                        &.money {
                            color: #FF5722;
                            font-weight: 600;
                        }
                    }
                }
            }
        }


    }
}

.upload-section {

    // 新增文件列表样式
    .list-item {
        display: flex;
        align-items: center;
        padding: 20rpx;
        background: #fff;
        border-radius: 20rpx;
        margin-bottom: 20rpx;

        .file-icon {
            width: 80rpx;
            height: 80rpx;
            margin-right: 20rpx;
        }

        .option {
            flex-direction: column; // 改为垂直布局
            align-items: flex-start;
            width: 80%;

            .file-info {
                width: 100%; // 占满整行

                .file-title {
                    white-space: nowrap; // 防止换行
                    overflow: hidden;
                    text-overflow: ellipsis; // 超出显示省略号
                    max-width: 500rpx; // 根据实际容器宽度调整
                    font-size: 23rpx;
                }

                .file-time {
                    font-size: 24rpx;
                    color: #999;
                }
            }

            .action-buttons {
                margin-top: 20rpx; // 增加上边距
                width: 100%;
                justify-content: flex-end; // 按钮右对齐
                button {
                    height: 50rpx;
                    line-height: 50rpx;
                    padding: 0 30rpx;
                    border-radius: 25rpx;
                    font-size: 24rpx;

                    &.download-button {
                        border: 2rpx solid #008EFF;
                        color: #008EFF;
                        background: #fff;
                        margin-top: 10rpx;
                    }

                    &.view-button {
                        background: #008EFF;
                        color: #fff;
                        border: none;
                        margin-top: 10rpx;
                    }
                }
            }
        }
    }
}

// 新增底部按钮样式
.footer {
    position: fixed;
    bottom: 40rpx;
    left: 30rpx;
    right: 30rpx;
    z-index: 10;

    .submit-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background: #008EFF;
        color: #fff;
        font-size: 32rpx;
        border-radius: 44rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 142, 255, 0.3);

        &:active {
            opacity: 0.9;
        }
    }
}
</style>